import playwrightApi from '../lib/playwright.js'
import { htmlToCheerio } from '../lib/cheerio.js'
import { projectConfig, rootDir, dataDir, saveProjectConfig } from '../config.js'
import fse from 'fs-extra'
import path from 'path'

class Sanfoundry {
  constructor() {}

  initRoute(koa) {
    koa.router.get('/', this.start.bind(this))
  }

  async start(ctx) {
    console.log('start')

    setTimeout(async () => {
      const data = await this.getHomeData()

      console.log('data', data.length)

      for (let i = projectConfig.contentIndex; i < data.length; i++) {
        const item = data[i]

        console.log('进度', i / data.length)

        await this.getContent(item.href, i)

        projectConfig.contentIndex = i
        saveProjectConfig()
      }
    }, 0)

    ctx.body = {
      code: 0,
      msg: '任务启动',
    }
  }

  async getContent(url, index) {
    console.log('getContent', url)
    const html = await playwrightApi.getHtml(url)

    const $ = htmlToCheerio(html)

    let result = []

    $('div.entry-content > p').each(function () {
      let html = $(this).html().split('<br>')
      let question = html[0].trim() // 第一行是题目
      let options = []

      // 倒数第二个是 “View Answer”，所以要排除掉
      for (let i = 1; i < html.length - 1; i++) {
        let opt = $('<div>').html(html[i]).text().trim() // 转换去掉标签
        if (opt) options.push(opt)
      }

      // 找到紧跟的答案 div
      let answerDiv = $(this).next('div.collapseomatic_content')
      let answerText = answerDiv.text().trim()

      // 提取答案选项和解释
      let answerOption = ''
      let explanation = ''

      // 使用正则表达式匹配答案选项（任意字母）
      const answerMatch = answerText.match(/Answer:\s*([A-Z])/i)
      if (answerMatch && answerMatch[1]) {
        answerOption = answerMatch[1].toUpperCase()
      }

      // 提取解释部分
      const explanationMatch = answerText.match(/Explanation:\s*(.+)/i)
      if (explanationMatch && explanationMatch[1]) {
        explanation = explanationMatch[1].trim()
      }

      if (answerText != '')
        result.push({
          question,
          options,
          answer: answerOption,
          explanation,
        })
    })

    fse.writeJSON(path.join(dataDir, index + '.json'), result)

    console.log(result)
  }

  async getHomeData() {
    console.log('getHomeData')

    const html = await playwrightApi.getHtml(
      'https://www.sanfoundry.com/1000-cyber-security-questions-answers/#introduction-ethical-hacking'
    )

    const $ = htmlToCheerio(html)

    let pages = []
    const data = []

    $('.sf-section').map(function () {
      const $section = $(this)
      const title = $section.find('h2').text().trim()

      // 获取所有链接
      const links = $section
        .find('a')
        .map(function () {
          return {
            text: $(this).text().trim(),
            href: $(this).attr('href'),
          }
        })
        .get() // .get() 将jQuery对象转换为数组

      if (!title) return
      if (!links.length) return

      // data.push({ title, links })
      pages = pages.concat(links)
    })

    return pages
  }
}

export default new Sanfoundry()
